<template>
  <div>
    <Estate></Estate>
    <div class="my-define-title1" style="display: flex; justify-content:space-between">
      <div>
        <!-- <svg-icon style="margin-right: 5px; width: 0.95rem; height: 0.95rem;" v-if="pageIcon" :icon-class="pageIcon" /> -->
        <svg-icon style="margin-right: 0px; width: 1.1rem; height: 1.1rem;" icon-class="guanzhustar" />
        {{pageTitle}}
      </div>
      <div style="">
        <el-dropdown trigger="click">
          <span class="el-dropdown-link">
            <i class="el-icon-plus" style="font-weight: 600;"></i>
            <!-- <svg-icon icon-class="icon-add"/> -->
          </span>
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item @click.native="addScene()"><svg-icon icon-class="newtable"
                style="width: 20px; height: 20px; position: relative; top:3px" />新建数据表</el-dropdown-item>
            <el-dropdown-item @click.native="addGroup()"><svg-icon icon-class="newbox"
                style="width: 20px; height: 20px; position: relative; top:3px" />新建分组</el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
      </div>
    </div>
    <div class="my-right-plus" :style="collapseStyle" @click="toggleSideBar">
      <i v-if="!isCollapse()" class="saas-iconfont saas-icon-zuoshuangjiantou"></i>
      <i v-else class="saas-iconfont saas-icon-youshuangjiantou"></i>
    </div>
    <div class="my-define-tab-content1">
      <el-scrollbar style="height: calc(100% - 80px);">
        <!-- style=" background:#13CE66" default-expand-all -->
        <el-tree ref="leftMenuTree" :props="treeProps" :data="sceneList" node-key="id" :expand-on-click-node="false"
          highlight-current :allow-drop="allowDrop" :allow-drag="allowDrag" @node-drop="handleDrop" draggable>
          <div style="" class="custom-tree-node" slot-scope="{ node, data }">
            <div v-if="!data.isEditing" @click="handlTreeMenuClick(data)">
              <svg-icon v-if="!data.isGroup" icon-class="icon-table" />
              {{ data.label }}
            </div>
            <div class="edit-input-content" :ref="'sceneEditInput_'+data.id" v-if="data.isEditing">
              <el-input v-model="data.label" size="mini" placeholder="请输入" style="width: 90%;"></el-input>
            </div>
            <div v-if="!data.isEditing" style="position: absolute;top: 0;right: 10px;">
              <el-dropdown trigger="click" placement="bottom-start">
                <span class="el-dropdown-link">
                  <svg-icon icon-class="icon-line-more" />
                </span>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item v-if="!data.isGroup" @click.native="doEditScene(data)">
                    <svg-icon icon-class="icon-edit" style="margin-right: 5px;" />
                    重命名
                  </el-dropdown-item>
                  <el-dropdown-item v-if="data.isGroup" @click.native="doEditGroup(data)">
                    <svg-icon icon-class="icon-edit" style="margin-right: 5px;" />
                    修改分组
                  </el-dropdown-item>
                  <el-dropdown-item v-if="false" @click.native="doAddSubScene(data)">
                    <svg-icon icon-class="icon-table" style="margin-right: 5px;" />新增表格
                  </el-dropdown-item>
                  <el-dropdown-item v-if="!data.isGroup" @click.native="doCopySubScene(data)">
                    <svg-icon icon-class="icon-table" style="margin-right: 5px;" />复制表格
                  </el-dropdown-item>
                  <el-dropdown-item @click.native="doRemoveScene(data)">
                    <svg-icon icon-class="icon-table" style="margin-right: 5px;" />删除
                  </el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
            </div>
          </div>
        </el-tree>
        <!-- <div class="my-cateogry-add my-cateogry-item1">
          <div class="my-cateogry-sub-item" @click="addScene()">
            <div>
              <svg-icon icon-class="icon-table" />
              <div class="my-category-title">
                新建数据表
              </div>
            </div>
            <div style="position: absolute;top: 0px;right: 5px;">
              <svg-icon icon-class="icon-add" style="width: 12px; height: 12px;" />
            </div>
          </div>
          <div class="my-cateogry-sub-item" @click="addGroup()">
            <div>
              <svg-icon icon-class="icon-table" />
              <div class="my-category-title">
                新建分组
              </div>
            </div>
            <div style="position: absolute;top: 0px;right: 5px;">
              <svg-icon icon-class="icon-add" style="width: 12px; height: 12px;" />
            </div>
          </div>
        </div> -->
      </el-scrollbar>
    </div>
    <el-dialog custom-class="my-common-dialog" width="30%" :visible.sync="sceneGroup.dialogShow" :show-close="false"
      :before-close="groupClose">
      <div class="my-define-dialog-title">
        {{sceneGroup.dialogTitle}}
        <div class="my-define-dialog-title-btn">
          <i @click="groupClose(false)" class="saas-iconfont saas-icon-caozuo-quanping-shousuo"></i>
        </div>
      </div>
      <el-form v-if="sceneGroup.dialogShow" size="mini" label-width="80px" ref="groupForm" :model="sceneGroup.groupForm"
        label-position="top">
        <el-row>
          <el-col :span="24" :prop="'label'" :rules="{
                    required: true, message: '请输入分组名称', trigger: 'change'}">
            <el-form-item label="">
              <el-input style="width: 100%; height: 32px; line-height: 32px;" placeholder="请输入分组名称"
                v-model="sceneGroup.groupForm.label"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24" style="margin-bottom: 40px;">
            <el-form-item label="请选择移入分组的数据">
              <!-- default-expand-all -->
              <el-tree :data="sceneList" node-key="id" :expand-on-click-node="false" highlight-current
                style=" max-height: 400px; overflow-y: auto;">
                <div style="" class="custom-tree-node" slot-scope="{ node, data }">
                  <div @click="doCheckGroup(data)">
                    <svg-icon v-if="!data.isGroup" icon-class="icon-table" />
                    {{ data.label }}
                  </div>
                  <div v-if="!data.isGroup" style="position: absolute;top: 0;right: 10px;">
                    <el-checkbox v-model="data.isChecked"></el-checkbox>
                  </div>
                </div>
              </el-tree>
            </el-form-item>
          </el-col>
          <el-col :span="24" style="text-align: right; position: fixed;bottom: 0rem; right: 0px; padding-right: 20px;">
            <el-form-item>
              <el-button type="primary" @click="handleGroupSave">确认</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
  import draggable from "vuedraggable"
  import Estate from '@/layout/components/Sidebar/Estate'
  import {
    mapGetters
  } from 'vuex'
  import {
    getScenes,
    saveScene,
    copyScene,
    removeScene,
    sortScene
  } from '@/api/system/scene'
  import {
    getOperationLog,
    getMsgCount
  } from '@/api/system/system'
  export default {
    name: 'sub-menu',
    components: {
      draggable,
      Estate
    },
    props: {
      pageTitle: {
        type: String,
        default: null
      },
      pageIcon: {
        type: String,
        default: null
      },
      sceneType: {
        type: Number,
        default: 0
      },
      defaultSceneId: {
        type: Number,
        default: 0
      }
    },
    watch: {
      sceneType: {
        handler(newValue, oldValue) {
          this.getData(0)
        }
      }
    },
    computed: {
      ...mapGetters(['routers', 'sidebar'])
    },
    data() {
      return {
        treeProps: {
          children: 'children',
          label: 'label'
        },
        allSceneList: [],
        sceneList: [],
        defineSceneList: [],
        menuOpeneds: [],
        activeMenuIndex: '',
        activeScene: '',
        userPower: [],
        activeFocus: '',
        hoverFocus: '',
        focusForm: {
          id: '',
          focusId: 0,
          label: '',
          icon: '',
          canEdit: true,
          isEditing: true,
          conditions: []
        },
        showTitle: '',
        showFocus: false,
        allColumnData: [],
        columnFinalData: [],
        columnFinalDefineData: [],
        editFocusLabel: false,
        sceneId: 0,
        columnKeyword: '',
        formData: null,
        formFieldTypeData: [{
          value: 1,
          label: '文本'
        }, {
          value: 2,
          label: '日期'
        }, {
          value: 3,
          label: '单选'
        }, {
          value: 4,
          label: '多选'
        }, {
          value: 5,
          label: '复选框'
        }, {
          value: 6,
          label: '多行文本'
        }],
        formConditionData: [],
        tryCount: 0,
        logData: [],
        showMessage: false,
        msgCount: 0,
        collapseStyle: {
          top: '0px',
          display: 'none'
        },
        currentScene: {},
        sceneGroup: {
          dialogShow: false,
          dialogTitle: '',
          groupForm: {
            id: 0,
            label: ''
          },
          defaultProps: {
            children: 'children',
            label: 'label'
          }
        }
      }
    },
    created() {
      this.getData(0)
    },
    mounted() {
      const {
        meta
      } = this.$route
      if (meta.frame) {
        this.collapseStyle.top = '45%'
      } else {
        this.collapseStyle.top = '45%'
      }
      setTimeout(() => {
        this.collapseStyle.display = 'block'
      }, 500)
    },
    methods: {
      getData(id) {
        this.userPower = this.$store.getters && this.$store.getters.userInfo.UserPower;
        // this.getMsgCount()
        getScenes({
          sceneType: this.sceneType,
          sceneId: this.defaultSceneId
        }).then(res => {
          if (res.status) {
            this.allSceneList = res.outputData.sceneList
            this.sceneList = this.allSceneList.filter((item) => {
              return item.visibility
            })
            this.defineSceneList = this.allSceneList.filter((item) => {
              return !item.visibility
            })
            var currentScene = null
            this.activeScene = ''
            if (id) {
              this.activeScene = id
            }
            if (this.sceneList.length == 0) {
              this.$$parent(this, "doClickScene", null)
            } else {
              let firstScene = null
              this.sceneList.forEach((item) => {
                if (item.id == this.activeScene) {
                  currentScene = item
                }
                if (!item.isGroup && !firstScene) {
                  firstScene = item
                }
                if (item.children) {
                  item.children.forEach((item2) => {
                    if (item2.id == this.activeScene) {
                      currentScene = item2
                    }
                    if (!item2.isGroup && !firstScene) {
                      firstScene = item2
                    }
                  })
                }
                if (currentScene) {
                  return false
                }
              })
              if (!currentScene && firstScene) {
                this.sceneId = firstScene.sceneId
                this.currentView = firstScene.viewName
                this.activeScene = firstScene.id
                setTimeout(() => {
                  this.handlTreeMenuClick(firstScene)
                }, 200)
              } else if (id && currentScene) {
                setTimeout(() => {
                  this.handlTreeMenuClick(currentScene)
                }, 200)
              } else {
                this.cancelSceneEdit()
              }
            }
          }
        })
      },
      addClickEvent() {
        document.addEventListener('mousedown', this.handleClickEvent, false)
      },
      removeClickEvent() {
        document.removeEventListener('mousedown', this.handleClickEvent, false)
      },
      handleClickEvent(e) {
        // var inputElem = eval("this.$refs.sceneEditInput_" + this.currentScene.id)[0]
        // console.log(this.currentScene)
        // if (inputElem && !inputElem.contains(e.target)) {
        //   this.doSaveScene(this.currentScene)
        //   this.removeClickEvent()
        // }
        var isIn = false
        let inputs = document.querySelectorAll('.edit-input-content')
        inputs.forEach((inputElm) => {
          if (inputElm.contains(e.target)) {
            isIn = true
            return false
          }
        })
        if (!isIn) {
          this.doSaveScene(this.currentScene)
          this.removeClickEvent()
        }
      },
      getMsgCount() {
        setTimeout(() => {
          getMsgCount({
            sceneType: this.sceneType
          }).then(res => {
            if (res.status) {
              this.msgCount = res.outputData.msgCount
            }
          })
        }, 1000)
      },
      toggleSideBar() {
        this.$store.dispatch('app/toggleSideBar')
      },
      isCollapse() {
        return !this.sidebar.opened
      },
      handlTreeMenuClick(data) {
        if (data.isGroup) {
          data.isExpend = !data.isExpend
          return
        }
        this.doClickSceneProcess(data);
      },
      doClickSceneProcess(data, id) {
        if (!data && id) {
          this.sceneList.forEach((item) => {
            if (item.id == id) {
              data = item
              return false
            }
            if (item.children) {
              item.children.forEach((item2) => {
                if (item2.id == id) {
                  data = item2
                  return false
                }
              })
            }
            if (data) {
              return false
            }
          })
        }
        if (!data && !data.id) {
          return
        }
        if (data.isGroup) {
          return
        }
        this.$refs.leftMenuTree.setCurrentKey(data.id)
        this.activeScene = data.id
        this.$$parent(this, "doClickScene", data)
        // this.getMsgCount()
        // this.$$parent(this, "DataList").then(data => {
        //   console.log(data) //data就是获取的值
        // })
        this.cancelSceneEdit()
      },
      addScene() {
        var index = this.sceneList.length + 1 + ''
        var subItem = {
          id: '',
          label: '未命名' + index,
          sceneId: 0,
          defineSceneId: 0,
          scenePId: 0,
          sceneType: this.sceneType,
          permission: '',
          viewName: '',
          icon: '',
          canEdit: true,
          sceneLevel: 1,
          isEditing: true,
          children: []
        }
        this.sceneList.unshift(subItem)
        this.currentScene = subItem
        setTimeout(() => {
          this.addClickEvent()
        }, 500)
      },
      doSaveScene(item) {
        if (!item.defineSceneId && !item.label) {
          this.doSpliceSceneChildren(item)
          return
        }
        saveScene({
          defineSceneId: item.defineSceneId,
          parentId: item.scenePId,
          sceneType: this.sceneType,
          sceneTitle: item.label
        }).then(res => {
          if (res.status) {
            item.isEditing = false
            this.getData(item.isGroup ? 0 : res.outputData.Id)
          }
        })
      },
      doEditScene(item) {
        this.cancelSceneEdit()
        item.isEditing = true
        this.currentScene = item
        setTimeout(() => {
          this.addClickEvent()
        }, 500)
      },
      doAddSubScene(item) {
        this.cancelSceneEdit()
        var index = item.children.length + 1 + ''
        var subItem = {
          id: '',
          label: '未命名' + index,
          sceneId: 0,
          defineSceneId: 0,
          parentId: item.defineSceneId,
          sceneType: this.sceneType,
          permission: '',
          viewName: '',
          icon: '',
          canEdit: true,
          sceneLevel: 2,
          isEditing: true
        }
        item.children.push(subItem)
        this.currentScene = subItem
        setTimeout(() => {
          this.addClickEvent()
        }, 100)
      },
      doCopySubScene(item) {
        copyScene({
          sceneId: item.sceneId,
          defineSceneId: item.defineSceneId
        }).then(res => {
          if (res.status) {
            this.getData(res.outputData.Id)
          }
        })
      },
      doSpliceSceneChildren(item) {
        var spliceIndex1 = -1
        var myIndex1 = 0
        this.sceneList.forEach((item1) => {
          if (item1.id == item.id && item1.scenePId == 0) {
            spliceIndex1 = myIndex1
            return false
          }
          myIndex1++
          if (item.defineSceneId == item1.scenePId) {
            var spliceIndex = -1
            var myIndex = 0
            item1.children.forEach((item2) => {
              if (item.id == item2.id) {
                spliceIndex = myIndex
                return false
              }
              myIndex++
            })
            if (spliceIndex > -1) {
              item1.children.splice(spliceIndex, 1)
              return false
            }
          }
        })
        if (spliceIndex1 > -1) {
          this.sceneList.splice(spliceIndex1, 1)
          return false
        }
      },
      doRemoveScene(item) {
        if (!item.defineSceneId) {
          this.doSpliceSceneChildren(item)
          return
        }
        removeScene({
          defineSceneId: item.defineSceneId
        }).then(res => {
          if (res.status) {
            this.getData(0)
          }
        })
      },
      cancelSceneEdit() {
        this.sceneList.forEach((item) => {
          item.isEditing = false
          if (item.children) {
            item.children.forEach((item2) => {
              item2.isEditing = false
            })
          }
        })
      },
      addGroup() {
        this.sceneList.forEach((item) => {
          item.isChecked = false
          if (item.children) {
            item.children.forEach((item2) => {
              item2.isChecked = false
            })
          }
        })
        this.sceneGroup.dialogShow = true
        this.sceneGroup.dialogTitle = '新增分组'
        this.sceneGroup.groupForm.defineSceneId = 0
        this.sceneGroup.groupForm.label = ''
      },
      groupClose() {
        this.sceneGroup.dialogShow = false
      },
      handleGroupSave() {
        var childIdList = []
        this.sceneList.forEach((item) => {
          if (item.isChecked && !item.isGroup) {
            childIdList.push(item.id)
          }
          if (item.children) {
            item.children.forEach((item2) => {
              if (item2.isChecked && !item2.isGroup) {
                childIdList.push(item2.id)
              }
            })
          }
        })
        saveScene({
          isGroup: 1,
          defineSceneId: this.sceneGroup.groupForm.defineSceneId,
          parentId: 0,
          sceneType: this.sceneType,
          sceneTitle: this.sceneGroup.groupForm.label,
          childIds: JSON.stringify(childIdList)
        }).then(res => {
          if (res.status) {
            this.groupClose()
            this.getData(0)
          }
        })
      },
      doEditGroup(data) {
        this.sceneGroup.dialogTitle = '修改分组'
        this.sceneGroup.groupForm = data
        this.sceneList.forEach((item) => {
          item.isChecked = false
          if (item.id == data.id) {
            if (item.children) {
              item.children.forEach((item2) => {
                item2.isChecked = true
              })
            }
          } else {
            if (item.children) {
              item.children.forEach((item2) => {
                item2.isChecked = false
              })
            }
          }
        })
        this.sceneGroup.dialogShow = true
      },
      doCheckGroup(data) {
        data.isChecked = !data.isChecked
      },
      allowDrop(draggingNode, dropNode, type) {
        if (!dropNode.data.isGroup && type == 'inner') {
          return false
        }
        if (draggingNode.data.isGroup) {
          if (type == 'inner') {
            return false
          }
          if (dropNode.data.sceneLevel == 2) {
            return false
          }
        }
        return true
      },
      allowDrag(draggingNode) {
        if (draggingNode.data.isEditing) {
          return false
        }
        return true
      },
      handleDrop(draggingNode, dropNode, dropType, ev) {
        sortScene({
          defineSceneId: draggingNode.data.defineSceneId,
          toId: dropNode.data.defineSceneId,
          dropType: dropType,
          sceneType: this.sceneType
        }).then(res => {
          if (res.status) {
            this.getData(0)
          }
        })
      }
    }
  }
</script>

<style rel="stylesheet/scss" lang="scss">
  .my-right-plus {
    position: fixed;
    left: 295px;
    height: 60px;
    line-height: 60px;
    top: 20px;
    background: #fff;
    border: solid 0.5px #eee;
    border-radius: 5px;
    padding: 0px 5px;
    z-index: 99;
    display: none;
  }

  .el-dropdown-link {
    cursor: pointer;
  }

  .el-tree-node__expand-icon {
    color: #999 !important;
    font-size: 14px !important;
  }

  .el-tree-node__expand-icon.is-leaf.el-icon-caret-right:before {
    display: none;
  }

  .my-right-plus .saas-iconfont {
    font-size: 14px;
    cursor: pointer;
    color: #303133;
  }

  .my-cateogry-item1 {
    margin-left: 5px;

    .my-cateogry-sub-item {
      cursor: pointer;
      margin-bottom: 5px;
      position: relative;

      .svg-icon {
        width: 13.5px;
        height: 13.5px;
        margin-right: 5px;
        vertical-align: 0px;
        cursor: pointer;
      }

      .my-category-title {
        overflow: hidden;
        position: absolute;
        left: 24px;
        right: 30px;
        color: #333;
        font-size: 14px;
        top: 0;
        max-height: 32px;
      }
    }

    .my-cateogry-sub-item.active-item {
      .svg-icon {
        fill: #1890ff;
      }

      .my-category-title {
        color: #1890ff;
      }
    }
  }

  .my-cateogry-add.my-cateogry-item1 {
    margin-top: 10px;
    padding-top: 10px;
    border-top: solid 1px #ddd;
  }

  .active-category {
    .svg-icon {
      // fill: #1890ff;
      fill: #333;
    }

    // color: #1890ff;
    color: #333;
  }

  .el-tree-node__content {
    height: 36px;
  }

  .el-dropdown-link .svg-icon {
    visibility: hidden;

    &:active {
      visibility: initial;
    }
  }

  .custom-tree-node {
    color: #333;
    flex: 1;
    display: block;
    position: relative;
    align-items: center;
    justify-content: space-between;
    font-size: 14px;

    &:active {
      .el-dropdown-link .svg-icon {
        visibility: initial;
      }
    }

    &:hover {
      .el-dropdown-link .svg-icon {
        visibility: initial;
      }
    }
  }
</style>
